package com.boot.security.server.service.impl.mffl.MfflConsultation;

import com.boot.security.server.dao.UserDao;
import com.boot.security.server.dao.mffl.*;
import com.boot.security.server.dto.LoginUser;
import com.boot.security.server.model.mffl.*;
import com.boot.security.server.model.mffl.Vo.MfflConsultationTimerVo;
import com.boot.security.server.page.table.PageTableHandler;
import com.boot.security.server.page.table.PageTableRequest;
import com.boot.security.server.page.table.PageTableResponse;
import com.boot.security.server.service.impl.mffl.WXPay.WXPayService;
import com.boot.security.server.utils.UserUtil;
import com.boot.security.server.utils.mffl.ProjectUtil;
import com.boot.security.server.utils.mffl.ReturnBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.boot.security.server.service.impl.mffl.MfflSystemMessages.MfflSystemMessagesImpl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import com.boot.security.server.service.impl.mffl.Mfflpublic.publicService;

/**
 * 咨询业务
 */
@Service
public class MfflConsultationService {
    @Autowired
    private MfflUserDao mfflUserDao;

    @Autowired
    private MfflConsultationDao mfflConsultationDao;

    @Autowired
    private MfflConsultationReplyDao mfflConsultationReplyDao;

    @Autowired
    private MfflConsultationlikeDao mfflConsultationlikeDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private RedisTemplate<String, Map<String, String>> redisTemplate;

    @Autowired
    private MfflOrderDao mfflOrderDao;

    @Autowired
    private MfflTypeDao mfflTypeDao;

    //微信支付
    @Autowired
    WXPayService wxPayService;

    //微信支付
    @Autowired
    private WXPayService wxpayservice;

    //支入支出表
    @Autowired
    private MfflProfitDao mfflProfitDao;


    //用户表
    @Autowired
    MfflUserDao mffluserdao;

    //公共功能
    @Autowired
    private publicService publicService;

    //推送
    @Autowired
    MfflSystemMessagesImpl MfflSystemMessagesImpl;

    //配置微信支付随机数
    @Value("${Pay.attach}")
    private String attach;

    /**
     * 微信支付
     *
     * @param payMerchantNumber 商户订单号
     * @param notifyurl         回调地址
     * @return
     */
    public ReturnBean ServicePay(String payMerchantNumber, String notifyurl) {
        MfflOrder bypaymerchantnumber = mfflOrderDao.getBypaymerchantnumber(payMerchantNumber);
        if (bypaymerchantnumber == null) {
            ReturnBean returnbean = new ReturnBean();
            returnbean.setReturnBean("106");
            returnbean.setMessage("当前商户号对应的，订单不存在");
            return returnbean;
        }
        ReturnBean returnBean = wxpayservice.WXPay(notifyurl, bypaymerchantnumber.getServiceName(), payMerchantNumber);
        return returnBean;
    }


    /**
     * 微信打赏回调
     *
     * @param map
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean WechatPayCallback(Map<String, String> map) throws Exception {
        System.out.println("访问回调");
        System.out.println(map);
        String paymerchantnumber = map.get("out_trade_no");//商户订单号
        String payNumber = map.get("transaction_id");      //交易单号

        String nonceStr = map.get("attach");      //随机数
        //验证随机数
        if (!attach.equals(nonceStr)) {
            System.out.println("验证随机数不通过");
            return false;
        }

        try {
            //订单操作
            MfflOrder Order = mfflOrderDao.getByPaymerchantNumberlocking(paymerchantnumber);
            //如果已支付返回true
            if (!(Order.getState() == 0 || Order.getState() == 5)) {
                return true;
            }

            //创建一个实体，防止在修改过程中其他信息改变的风险
            MfflOrder mfflOrder = new MfflOrder();
            mfflOrder.setId(Order.getId());
            mfflOrder.setPayNumber(payNumber);
            mfflOrder.setUpdtaeTime(new Date());
            mfflOrder.setState(1);
            mfflOrderDao.update(mfflOrder);

            //打赏数+1
            MfflConsultationReply replydata = mfflConsultationReplyDao.getById(Order.getProductId().longValue());
            MfflConsultationReply mffCtr = new MfflConsultationReply();
            mffCtr.setId(replydata.getId());
            mffCtr.setRewardnumber(replydata.getRewardnumber() + 1);
            mfflConsultationReplyDao.update(mffCtr);

            //MfflConsultation mfft = mfflConsultationDao.getById(Order.getProductId().longValue());
            //用户支出信息
            Date date = new Date();
            MfflProfit mp = new MfflProfit();
            mp.setOrderId(Order.getId().intValue());
            mp.setUserId(Order.getUserid()); //用户id
            mp.setServciceName("打赏");
            mp.setState(0);                      //0支出，1收益,
            mp.setMoney(Order.getMoney());   //支出不扣点
            mp.setSettlement(1);                 //0未结算，1已经算
            mp.setCreateTime(date);
            mp.setSettlementTime(date);
            mp.setDeduction(0.0);
            mp.setUpdateTime(date);
            mfflProfitDao.save(mp);

            //律师支出
            MfflProfit mlp = new MfflProfit();
            mlp.setOrderId(Order.getId().intValue());
            mlp.setUserId(Order.getTypeid()); //律师id
            mlp.setServciceName("打赏");
            mlp.setState(1);               //0支出，1收益,
            mlp.setMoney(Order.getMoney());   //律师收益显示已扣点金额
            mlp.setSettlement(0);          //0未结算，1已经算
            mlp.setCreateTime(date);
            mlp.setSettlementTime(date);
            mlp.setDeduction(0.0);   //平台扣点金额
            mlp.setUpdateTime(date);
            mfflProfitDao.save(mlp);
            //添加到用户金额上

            // 问题数据
            MfflConsultation byId = mfflConsultationDao.getById(replydata.getConsultationId().longValue());
            //推送
            MfflSystemMessagesImpl.sendMessage(publicService.MessageModel((byId.getServiceId() == 1 ? "[免费咨询]" : "[专业咨询]") + "咨询被打赏", byId.getPayMerchantNumber()), byId.getServiceId().toString(), replydata.getConsultationId(), Order.getTypeid());


            //修改律师个人账户金额
            MfflUser userInfoAll = mffluserdao.getmffluser(Order.getTypeid());
            MfflUser mu = new MfflUser();
            mu.setId(userInfoAll.getId());
            mu.setMoney(ProjectUtil.addition(userInfoAll.getMoney(),Order.getMoney()));
            mu.setUpdateTime(new Date());
            mffluserdao.update(mu);
        } catch (Exception e) {
            e.printStackTrace();
            //防止意外错误
            throw new Exception("异常错误");
        }
        return true;
    }


    /**
     * 查询订单状态
     * <p>
     * 如果查询微信订单为已支付并且本地order未改变，则修改状态
     *
     * @param payMerchantNumber
     * @return
     */
    public ReturnBean orderquery(String payMerchantNumber) throws Exception {
        ReturnBean returnbean = new ReturnBean();
        try {
            Map<String, String> orderquery = wxpayservice.orderquery(payMerchantNumber);
            MfflOrder Order = mfflOrderDao.getByPaymerchantNumberlocking(payMerchantNumber);
            if (!(orderquery.containsKey("trade_state") && orderquery.get("trade_state").equals("SUCCESS")) || Order.getState() == 0) {
                MfflOrder mfflOrder = new MfflOrder();
                mfflOrder.setId(Order.getId());
                mfflOrder.setState(5);//支付中
                mfflOrder.setUpdtaeTime(new Date());
                mfflOrderDao.update(mfflOrder);
                returnbean.setDatas(orderquery);
                return returnbean;
            }

            //订单操作
            String payNumber = orderquery.get("transaction_id");
            //如果状态未改变则改变状态
            if (Order.getState() == 0 || Order.getState() == 5) {
                //创建一个实体，防止在修改过程中其他信息改变的风险
                MfflOrder mfflOrder = new MfflOrder();
                mfflOrder.setId(Order.getId());
                mfflOrder.setPayNumber(payNumber);
                mfflOrder.setUpdtaeTime(new Date());
                mfflOrder.setState(1);
                mfflOrderDao.update(mfflOrder);

                //打赏数+1
                MfflConsultationReply replydata = mfflConsultationReplyDao.getById(Order.getProductId().longValue());
                MfflConsultationReply mffCtr = new MfflConsultationReply();
                mffCtr.setId(replydata.getId());
                mffCtr.setRewardnumber(replydata.getRewardnumber() + 1);
                mfflConsultationReplyDao.update(mffCtr);

                //MfflConsultation mfft = mfflConsultationDao.getById(Order.getProductId().longValue());
                //用户支出信息
                Date date = new Date();
                MfflProfit mp = new MfflProfit();
                mp.setOrderId(Order.getId().intValue());
                mp.setUserId(Order.getUserid()); //用户id
                mp.setServciceName("打赏");
                mp.setState(0);                      //0支出，1收益,
                mp.setMoney(Order.getMoney());   //支出不扣点
                mp.setSettlement(1);                 //0未结算，1已经算
                mp.setCreateTime(date);
                mp.setSettlementTime(date);
                mp.setDeduction(0.0);
                mp.setUpdateTime(date);
                mfflProfitDao.save(mp);

                //律师支出
                MfflProfit mlp = new MfflProfit();
                mlp.setOrderId(Order.getId().intValue());
                mlp.setUserId(Order.getTypeid()); //律师id
                mlp.setServciceName("打赏");
                mlp.setState(1);               //0支出，1收益,
                mlp.setMoney(Order.getMoney());   //律师收益显示已扣点金额
                mlp.setSettlement(0);          //0未结算，1已经算
                mlp.setCreateTime(date);
                mlp.setSettlementTime(date);
                mlp.setDeduction(0.0);   //平台扣点金额
                mlp.setUpdateTime(date);
                mfflProfitDao.save(mlp);
                //添加到用户金额上

                // 问题数据
                MfflConsultation byId = mfflConsultationDao.getById(replydata.getConsultationId().longValue());

                //推送
                MfflSystemMessagesImpl.sendMessage(publicService.MessageModel((byId.getServiceId() == 1 ? "[免费咨询]" : "[专业咨询]")+ "咨询被打赏", byId.getPayMerchantNumber()), byId.getServiceId().toString(), replydata.getConsultationId(), Order.getTypeid());

                //修改律师个人账户金额
                MfflUser userInfoAll = mffluserdao.getmffluser(Order.getTypeid());
                MfflUser mu = new MfflUser();
                mu.setId(userInfoAll.getId());
                mu.setMoney(ProjectUtil.addition(userInfoAll.getMoney() , Order.getMoney()));
                mu.setUpdateTime(new Date());
                mffluserdao.update(mu);
                return returnbean;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("异常错误");
        }
        return returnbean;
    }


    /**
     * 退款操作
     *
     * @param ayMerchantNumber
     * @return
     * @throws Exception
     */
    @Transactional
    public ReturnBean cancel(String ayMerchantNumber) throws Exception {
        //获取订单信息
        return wxpayservice.weChatrefund(ayMerchantNumber, null, "撤销发布", 0);
    }


    /**
     * 咨询热度
     *
     * @param id 咨询id
     * @return
     */
    public ReturnBean setHot(Long id) {
        ReturnBean returnbean;
        LoginUser loginUser = UserUtil.getLoginUser();
        //查询当前热度，增加
        MfflConsultation byId = mfflConsultationDao.getById(id);

        if (byId.getTradingState() == 3) {
            return new ReturnBean("201", "当前咨询已取消发布，无法完成此操作");
        }
        if (byId.getDeleteState() == 0) {
            return new ReturnBean("201", "当前咨询已删除，无法完成此操作");
        }

        MfflConsultation mfflConsultation = new MfflConsultation();
        mfflConsultation.setId(id);
        mfflConsultation.setHot(byId.getHot() + 1);//每次热度加1
        mfflConsultation.setUpdateTime(null);
        int update = mfflConsultationDao.update(mfflConsultation);
        if (update == 1) {
            returnbean = new ReturnBean();
            returnbean.setReturnBean("200");
        } else {
            returnbean = new ReturnBean();
            returnbean.setReturnBean("105");
        }
        return returnbean;
    }

    /**
     * 关系咨询同时关闭订单
     *
     * @param id 咨询id
     */
    @Transactional
    public void delConsultationAndOrder(Long id) {
        mfflConsultationDao.delete(id);
        mfflOrderDao.deleteOrderByProductId(id);
    }

    /**
     * 获取自己参与过的免费/专业咨询
     *
     * @param request
     * @return
     */
    public ReturnBean<MfflConsultation> participatelist(PageTableRequest request) {
        LoginUser loginUser = UserUtil.getLoginUser();
        PageTableResponse handle = new PageTableHandler(new PageTableHandler.CountHandler() {
            @Override
            public int count(PageTableRequest request) {
                return mfflConsultationDao.participatecount(request.getParams());
            }
        }, new PageTableHandler.ListHandler() {
            @Override
            public List<MfflConsultation> list(PageTableRequest request) {
                return mfflConsultationDao.participatecountlist(request.getParams(), request.getOffset(), request.getLimit());
            }
        }).handle(request);

        List<MfflConsultation> MfflConsultationdata = (List<MfflConsultation>) handle.getData();

        for (int i = 0; i < MfflConsultationdata.size(); i++) {
            Integer type = MfflConsultationdata.get(i).getType();
            MfflType byId = mfflTypeDao.getById(type.longValue());
            MfflConsultationdata.get(i).setTypename(byId.getName());
        }
        ReturnBean returnBean = new ReturnBean();
        returnBean.setDatas(handle);
        return returnBean;
    }

    /**
     * 获取定时任务要处理的数据
     *
     * @return
     */
    public List<MfflConsultation> getTimerTaskData(Long ConfirmTime, Long RefuseTime) {
        return mfflConsultationDao.getTimerTaskData(ConfirmTime, RefuseTime);
    }

    public Integer update(MfflConsultation mfflConsultation) {
        return mfflConsultationDao.update(mfflConsultation);
    }
}
